<?php

namespace App\Filament\Resources\CategoryResource\Pages;

use App\Filament\Resources\CategoryResource;
use App\Models\Book;
use App\Service\BqsService;
use Filament\Actions;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Filament\Tables\Actions\Action;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class ListCategories extends ListRecords
{

    protected static string $resource = CategoryResource::class;

    protected function getHeaderWidgets(): array
    {
        return [
          CategoryResource\Widgets\CategoryOverview::class  //
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            Actions\CreateAction::make(),
            Actions\Action::make('tree')
                ->icon('heroicon-m-list-bullet')
                ->label('分类总览')
                ->url(fn (): string => static::$resource::getUrl('tree')),
            Actions\Action::make('bqs')
                ->label('热门小说TP25')
                ->form([
                    TextInput::make('category')
                    ->label('分类')
                    ->placeholder('请输入分类名称')
                    ->required()
                ])
                ->action(fn($data) => $this->updateTop($data) )
        ];
    }

    private function updateTop($data)
    {
        $data = BqsService::top250($data['category']);
        foreach ($data as $item) {
            Book::updateOrCreate(
                ['title'=>$item['name']],
                [
                    'category_id'=>18,
                    'img'=> BqsService::downloadImg($item['img']),
                    'description'=>$item['desc'],
                    'author'=>$item['author'],
                    'tag'=> [$item['type']]
                ]
            );
        }
        return true;
    }


}
